package com.haha.helloworld.broadcast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.haha.helloworld.R;

public class BroadActivity extends AppCompatActivity {
    private Button btn1;
    private TextView tv_test;
    private MyBroadcast myBroadcast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broad);
        btn1=(Button)findViewById(R.id.btn1);
        tv_test=(TextView)findViewById(R.id.tv_test);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(BroadActivity.this,BroadActivity2.class);
                startActivity(intent);
            }
        });
        myBroadcast=new MyBroadcast();
        //过滤广播请求
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.haha.helloworld");
        //传入接收广播的类  和  过滤广播请求
        LocalBroadcastManager.getInstance(this).registerReceiver(myBroadcast,intentFilter);
    }

    //接收广播的类
    private class MyBroadcast extends BroadcastReceiver{
        //接收广播的行为
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()){
                case "com.haha.helloworld":
                    tv_test.setText("接收到了广播的行为："+intent.getAction());
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //有注册必然有取消注册，这里在生命周期结束的时候去取消注册
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myBroadcast);
    }
}